import { defineComponent, onMounted, onUnmounted, reactive, ref } from "vue";
import styles from "./Timedown.module.scss";
import { useStore as useIndexStore } from "@/store/index";

export default defineComponent({
  setup() {
    const indexStore = useIndexStore();
    const state = reactive({
      days: '0',
      hours: '00',
      minutes: '00',
      seconds: '00',
    })
    const timing = ref(null as any);
    const timingSet = () => {
      const until_time = new Date(indexStore.info.until_time);
      const now_time = new Date();
      if (now_time < until_time) {
        const timeDiff = until_time.getTime() - now_time.getTime();
        state.days = Math.floor(timeDiff / (1000 * 60 * 60 * 24)).toString();
        state.hours = Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString().padStart(2, '0');
        state.minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60)).toString().padStart(2, '0');
        state.seconds = Math.floor((timeDiff % (1000 * 60)) / 1000).toString().padStart(2, '0');
      } else {
        state.days = '0';
        state.hours = '00';
        state.minutes = '00';
        state.seconds = '00';
      }
    }
    onMounted(() => {
      timingSet();
      timing.value = setInterval(() => {
        timingSet();
      }, 1000)
    })
    onUnmounted(() => {
      clearInterval(timing.value);
    })
    return () => (
      <div class={styles.days}>{state.days}天{state.hours}:{state.minutes}:{state.seconds}</div>
    )
  }
})